<?php
/**
 * Created by PhpStorm.
 * User: Hanson
 * Date: 2016/9/25
 * Time: 23:08
 */

namespace App\Repository;


use App\Model\Lost;
use App\Model\Permission;
use Carbon\Carbon;

class LostRepository
{
    /**
     * @var Lost
     */
    protected $lost;

    public function __construct(Lost $lost)
    {
        $this->lost = $lost;
    }

    public function search($payload = [])
    {
        $query = $this->lost;

        if($payload['operatorId'] ?? null){
            $query = $query->where('operator_id', $payload['operatorId']);
        }

        if($payload['publisher'] ?? null){
            $query = $query->where('publisher', $payload['publisher']);
        }

        if(array_key_exists('status', $payload) && $payload['status'] !== ''){
            $query = $query->where('status', $payload['status']);
        }

        if(array_key_exists('role', $payload) && $payload['role'] !== ''){
            $query = $query->where('role', $payload['role']);
        }

        return $query->orderBy('created_at', 'desc')->paginate(20);
    }

    public function getCateringPublishers()
    {
        return $this->lost->select(\DB::raw('DISTINCT(publisher)'))->whereRole(1)->get();
    }

    public function getCateringOperators()
    {
        return $this->lost->select(\DB::raw('DISTINCT(operator_id)'))->whereRole(1)->where('operator_id', '!=', null)->get();
    }

    /**
     * 获取所有失物
     *
     * @return \Illuminate\Database\Eloquent\Collection|static[]
     */
    public function all()
    {
        return Lost::all();
    }

    public function find($id)
    {
        return $this->lost->find($id);
    }

    public function findUnFinishById($id)
    {
        return $this->lost->where('status', Lost::AUDITED)->where('id', $id)->first();
    }

    /**
     * 获取已审核招领
     *
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function getAudit()
    {
        return $this->lost->with('user')->where('status', Lost::AUDITED)->orderBy('updated_at', 'desc')->paginate(20);
    }

    /**
     * 获取未审核招领
     *
     * @return \Illuminate\Database\Eloquent\Collection|static[]
     */
    public function getPending()
    {
        return $this->lost->with('user')->where('status', Lost::PENDING)->orderBy('id', 'desc')->get();
    }

    public function changeStatus($id, $status)
    {
        return $this->lost->where('id', $id)->update(['status' => $status]);
    }

    /**
     * 返回用户的发布成功招领记录 （或者今天的记录）
     *
     * @param $openId
     * @param bool $today
     * @return array|\Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model|null|\stdClass|static|static[]
     */
    public function getByPublisher($openId, $today = false)
    {
        $query = Lost::where('publisher', $openId)->where('status', '!=', Lost::DISAPPROVAL);

        return $today ? $query->whereDate('created_at', Carbon::today()->toDateString())->first() : $query->get();
    }

    /**
     * 获取失主为某学号的所有失物记录
     *
     * @param $number
     * @return \Illuminate\Database\Eloquent\Collection|static[]
     */
    public function getByNumber($number)
    {
        return $this->lost->with('user')->where('number', $number)->get();
    }

    public function getAuditByNumber($number)
    {
        return $this->lost->with('user')->where('number', $number)->whereIn('status', [Lost::AUDITED, Lost::FINISH])
            ->orderBy('id', 'desc')->get();
    }

    /**
     * 根据失物ID更新失主信息
     *
     * @param $id
     * @param $user
     * @return bool
     */
    public function updateUser($id, $user)
    {
        return $this->lost->where('id', $id)->update([
            'class' => $user->class,
            'name' => $user->name
        ]);
    }

    /**
     * 发放饭卡，修改状态为已完成
     *
     * @param $id
     * @return bool
     */
    public function finishLost($id)
    {
        return $this->lost->where('id', $id)->update(['status' => Lost::FINISH, 'operator_id' => \Auth::guard('wechat')->user()->id]);
    }

    /**
     * 增加招领记录
     *
     * @param $openId
     * @param $cover
     * @param $description
     * @param $number
     * @return Lost
     */
    public function add($openId, $cover, $description, $number)
    {
        return Lost::create(['publisher' => $openId, 'description' => $description, 'number' => $number, 'status' => Lost::PENDING, 'cover' => $cover]);
    }

    public function sameLostToday($number, $description)
    {
        return $this->lost->where('number', $number)->where('description', $description)->whereDate('created_at', Carbon::today()->toDateString())->first();
    }

    public function getLostAuditor()
    {
        return $permissions = Permission::where('name', 'lost_audit')->first()->users();
    }

    /**
     * 获取招领数量（除去审核不通过）
     *
     * @return int
     */
    public function getCount()
    {
        return $this->lost->where('status', '!=', 3)->count();
    }

    public function getFinishCount($today = false)
    {
        $query = $this->lost;

        if($today){
            $query = $query->whereDate('created_at', Carbon::today()->toDateString());
        }

        return $query->whereStatus(Lost::FINISH)->count();
    }

}